<template>
  <div>
    <Dialog
      v-model="showDialog"
      :title="`${addConfigData ? '编辑' : '添加'}配置`"
      width="750px"
      :before-close="cancel"
    >
      <el-form
        v-loading="loading"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="150px"
        label-position="top"
        class="ruleForm-w"
        status-icon
      >
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>基础配置</span>
            </div>
          </template>
          <el-form-item :label="`名称`" prop="name">
            <el-input
              v-model="ruleForm.name"
              maxlength="20"
              show-word-limit
              clearable
              :placeholder="`请填写名称`"
            />
          </el-form-item>
          <el-form-item :label="`平台类型`">
            <el-select
              v-model="ruleForm.externalPlatformType"
              placeholder="请选择关系"
              @change="externalPlatformTypeChange"
            >
              <el-option
                v-for="ele in typeTopList"
                :key="ele.platformType"
                :label="ele.title"
                :value="ele.platformType"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="`配置标识`" prop="unique">
            <el-input
              v-model="ruleForm.unique"
              maxlength="100"
              show-word-limit
              clearable
              :placeholder="`置标识自由输入`"
            />
          </el-form-item>

          <el-form-item :label="`描述`" prop="remark">
            <el-input
              v-model="ruleForm.remark"
              maxlength="200"
              type="textarea"
              row="3"
              show-word-limit
              clearable
              :placeholder="`请填写描述`"
            />
          </el-form-item>
        </el-card>

        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>字段配置</span>
            </div>
          </template>
          <div
            v-show="jsonConfig.length"
            class="enumeration"
            v-for="(item, index) in jsonConfig"
            :key="index"
          >
              <!-- 文本 -->
              <el-form-item
                v-if="item.type == 'text'"
                v-show="item.showType"
                :label="`${item.paramTitle}`"
                :prop="'jsonConfig.' + index + '.paramValue'"
                :rules="[
                  {
                    required: item.required,
                    validator: validatePass,
                  },
                ]"
                label-width="100%"
              >
                <el-input
                  clearable
                  type="text"
                  :disabled="customUpdate == 0 || !item.allowUpdate||(addConfigData&&item.paramName=='wechatPlatformAuthName')"
                  :placeholder="`请输入${item.paramName}`"
                  v-model="item.paramValue"
                  @change="paramValueOnChange(item)"
                >
                </el-input>
              </el-form-item>

              <!-- 带输入建议的文本 -->
              <!-- {{ item.paramValue }} -->
              <el-form-item
                v-if="item.type == 'text_hint'"
                v-show="item.showType"
                :label="`${item.paramTitle}`"
                :prop="'jsonConfig.' + index + '.paramValue'"
                :rules="[
                  {
                    required: item.required,
                    validator: validatePass,
                  },
                ]"
                label-width="100%"
              >
                <el-autocomplete
                  :fetch-suggestions="querySearch"
                  value-key="val"
                  clearable
                  :disabled="customUpdate == 0 || !item.allowUpdate"
                  :placeholder="`请输入${item.paramName}`"
                  v-model="item.paramValue"
                  @click.left="setTextHint(item.variables)"
                  @change="paramValueOnChange(item)"
                >
                  <template #default="props">
                    <span class="link">{{ props.item.desc }}</span>
                  </template>
                </el-autocomplete>
              </el-form-item>

              <!-- 数字 -->

              <el-form-item
                v-if="item.type == 'number'"
                v-show="item.showType"
                :label="`${item.paramTitle}`"
                :prop="'jsonConfig.' + index + '.paramValue'"
                :rules="[
                  {
                    required: item.required,
                    validator: validatePass,
                  },
                ]"
                label-width="100%"
              >
                <el-input-number
                  v-if="item.type == 'number'"
                  v-show="item.showType"
                  v-model="item.paramValue"
                  @change="paramValueOnChange(item)"
                />
              </el-form-item>

              <!-- 单选 -->
              <el-form-item
                v-if="item.type == 'radio'"
                v-show="item.showType"
                :label="`${item.paramTitle}`"
                :prop="'jsonConfig.' + index + '.paramValue'"
                :rules="[
                  {
                    required: item.required,
                    validator: validatePass,
                  },
                ]"
                label-width="100%"
              >
                <el-radio-group
                  :disabled="customUpdate == 0 || !item.allowUpdate"
                  :placeholder="`请输入${item.paramName}`"
                  v-model="item.paramValue"
                  @change="paramValueOnChange(item)"
                >
                  <el-radio
                    v-for="(el, idx) in item.variables"
                    :key="idx"
                    :label="el.val"
                    >{{ el.desc }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>

              <!-- 多选 -->
              <el-form-item
                v-if="item.type == 'checkbox'"
                v-show="item.showType"
                :label="`${item.paramTitle}`"
                :prop="'jsonConfig.' + index + '.paramValue'"
                :rules="[
                  {
                    required: item.required,
                    validator: validatePass,
                  },
                ]"
                label-width="100%"
              >
                <el-checkbox-group
                  :disabled="customUpdate == 0 || !item.allowUpdate"
                  :placeholder="`请输入${item.paramName}`"
                  v-model="item.paramValue"
                  @change="paramValueOnChange(item)"
                >
                  <el-checkbox
                    v-for="(el, idx) in item.variables"
                    :key="idx"
                    :label="el.val"
                  >
                    {{ el.desc }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <!-- 下拉 -->
              <el-form-item
                v-if="item.type == 'select_one' || item.type == 'select_more'"
                v-show="item.showType"
                :label="`${item.paramTitle}`"
                :prop="'jsonConfig.' + index + '.paramValue'"
                :rules="[
                  {
                    required: item.required,
                    validator: validatePass,
                  },
                ]"
                label-width="100%"
              >
                <el-select
                  filterable
                  clearable
                  :multiple="item.type == 'select_more'"
                  :disabled="customUpdate == 0 || !item.allowUpdate"
                  :placeholder="`请输入${item.paramName}`"
                  v-model="item.paramValue"
                  @change="paramValueOnChange(item)"
                >
                  <el-option
                    v-for="el in item.variables"
                    :key="el.val"
                    :label="el.desc"
                    :value="el.val"
                  />
                </el-select>
              </el-form-item>
              <el-form-item v-if="!addConfigData&&item.type == 'text_hide'"  label="微信公众号绑定"               
              :prop="'jsonConfig.' + index + '.paramValue'"
              label-width="100%">
              <div>
                <div class="scan-qrcode">
                  <div class="qrcode-wrapper">
                    <img class="qrcode" :src="qrcode ? qrcode : HomeQRCode" alt="登录二维码"/>
                    <div class="status-cover" v-if='!qrcode'>
                      <div>请点击生成二维码</div>
                    </div>
                    <div  class="status-cover" v-if='qrcode&&verify'>
                        绑定成功
                      </div>
                  </div>
                  <div class="scan-tips">
                    <div class="scan-tips-font">1.点击生成二维码2.微信扫码绑定3.点击验证获取绑定结果</div>
                    <el-button @click="toCreateCode">生成二维码</el-button>
                    <el-button @click="toVerify">点击验证</el-button>
                  </div>
                </div>
              </div>
            </el-form-item>

          </div>
          <div v-show="!jsonConfig.length">暂无配置</div>
        </el-card>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="formValidate(ruleFormRef)">确定</el-button>
        </span>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts" setup>
import * as QRCode from "qrcode";
import HomeQRCode from "@/assets/login/home_qrcode.png";
import type { FormInstance, FormRules } from "element-plus";
import sysConfigApi from "@/api/sysConfigApi";
const props = defineProps({
  showDialog: Boolean,
  addConfigType: String,
  addConfigData: Object,
});
const Route = useRoute();
const store=useStore();
const loading = ref(false);
const { showDialog, addConfigData, addConfigType } = toRefs(props);
const ruleFormRef = ref<FormInstance>();
const customUpdate = ref(0);
const ruleForm = ref({
  name: "",
  remark: "",
  unique: "",
  externalType: "", // 大类
  externalPlatformType: "", // 平台类型
  jsonConfig: "",
});
const jsonConfig = ref([] as any);
const typeList = ref([
  { id: "sms", name: "短信" },
  { id: "pay", name: "支付" },
  { id: "weChat", name: "微信" },
  { id: "email", name: "邮件" },
]);
const typeTopList = ref([] as any);
// const channelTypeList = ref([
//   { id: "wx_pay", name: "微信支付" },
//   { id: "yun_feng", name: "云峰支付" },
//   { id: "weChat", name: "微信" },
//   { id: "ali_pay", name: "1邮件" },
//   { id: "heMi_pay", name: "2邮件" },
//   { id: "email", name: "3邮件" },
// ]);
// const validateParamValue = (rule: any, value: any, callback: any) => {
//
//
//   let isCallback = false
//   if(jsonConfig.value.length) {
//     jsonConfig.value.forEach((item: any, idx: any)=>{
//     if(jsonConfig.value[idx].paramValue) {
//       isCallback = true
//       return
//     }
//   })
//   }

//   if (isCallback) {
//     callback(new Error("请输入"))
//   } else {
//     callback()
//   }
// }
const validatePass = (rule: any, value: any, callback: any) => {
  //

  //
  // if (value === '') {

  // } else {
  //   callback()
  // }
  callback();
};
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入", trigger: ["blur", "change"] }],
  // paramValue: [{ validator: validateParamValue, trigger: 'blur' }],
});
watch(showDialog, (val) => {
  if (val) {
    if (addConfigType?.value) {
      ruleForm.value.externalType = addConfigType?.value;
    }
    if (addConfigData?.value) {
      ruleForm.value = {
        name: addConfigData.value.name,
        remark: addConfigData.value.remark,
        unique: addConfigData.value.unique,
        externalType: addConfigData.value.externalType, // 大类
        externalPlatformType: addConfigData.value.externalPlatformType, // 平台类型
        jsonConfig: addConfigData.value.jsonConfig,
      };
    }
    getPlatforms(ruleForm.value.externalType);
  }
});
const qrcode=ref('');
const verify=ref('');
const toCreateCode=async()=>{
  if(jsonConfig.value[0]['paramValue']){
      let params={
      merchantId:store.state.user.merchantId,
      authName:jsonConfig.value[0]['paramValue']
    }
    let rs: any = await sysConfigApi.wechatPlatformAuth(params);
    if(rs.code==200){
      QRCode.toDataURL(rs.payload.url, {margin: 0}).then(val => {
        qrcode.value = val
      })
    }
  }else{
    ElMessage.warning("请先填写微信公众号名称");
  }

}
const toVerify=async()=>{
  //此处放置验证接口
  let params={
    merchantId:store.state.user.merchantId,
    authName:jsonConfig.value[0]['paramValue']
  }
  let rs: any = await sysConfigApi.merchantAuthSearch(params);
  if(rs.code==200){
    if(rs.payload.isBind==1){
      jsonConfig.value[1]['paramValue']=rs.payload.wechatComponentAuthVo.id//放传回来的id
      verify.value='绑定成功'
    }else{
      ElMessage.warning("绑定未完成...请稍等");
    }
  }
}
const formValidate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      submitForm();
    } else {
    }
  });
};

const paramValueOnChange = (item: any) => {
  jsonConfig.value.forEach((el: any) => {
    // debugger
    // if(item.paramName == el.belongFieldName) {
    //   el.paramValue.typeOf == 'string' ? el.paramValue = '' : el.paramValue = []
    // }
    if(item.paramValue && !el.belongFieldName){
      return ;
    }
    if(item.paramName != el.belongFieldName){
      return ;
    }
    if (item.paramValue == el.belongFieldVal) {
      el.showType = true;
    }else{
      el.showType = false;
    }
  });
};

// interface LinkItem {
//   val: string
//   desc: string
// }
const restaurants = ref([]);

const setTextHint = (val: any) => {
  restaurants.value = val;
};
// 输入提示
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value;
  cb(results);
};

const createFilter = (queryString: string) => {
  return (restaurant: any) => {
    return restaurant.desc.toLowerCase().indexOf(queryString.toLowerCase()) >= 0;
  };
};

const getPlatforms = async (type: string) => {
  let rs: any = await sysConfigApi.getPlatforms({ content: type });
  if (rs.code === 200) {
    typeTopList.value = rs.payload;
    ruleForm.value.externalPlatformType =
      ruleForm.value.externalPlatformType || typeTopList.value[0].platformType;
    externalPlatformTypeChange();
  }
};

const externalPlatformTypeChange = () => {
  let isAddConfigData = Boolean(addConfigData?.value);
  typeTopList.value.forEach((item: any, idx: any) => {
    if (item.platformType == ruleForm.value.externalPlatformType) {
      customUpdate.value = item.customUpdate;
      if (isAddConfigData) {
        let jsonConfigData = JSON.parse(addConfigData?.value?.jsonConfig);
        if (item.params) {
          item.params.forEach((el: any) => {
            for (let key in jsonConfigData) {
              if (el.paramName == key) {
                el["paramValue"] = jsonConfigData[key];
              }
            }
          });
        }
      }
      getPlatformsChange(typeTopList.value[idx].params);
    }
  });
};
const getPlatformsChange = (params: any[]) => {
  if (params) {
    jsonConfig.value = [];
    params.forEach((item: any, index) => {
      let showType = true;
      if (item.belongFieldName) {
        showType = false;
      }
      jsonConfig.value.push({
        paramName: item.paramName,
        paramTitle: item.paramTitle,
        allowUpdate: item.allowUpdate,
        paramValue: item.paramValue || item.fillValue || "",
        required: item.required,
        type: item.type,
        variables: item.variables,
        belongFieldName: item.belongFieldName,
        belongFieldVal: item.belongFieldVal,
        showType: showType,
      });

      if (
        jsonConfig.value[index].paramValue &&
        (jsonConfig.value[index].type == "select_more" ||
          jsonConfig.value[index].type == "checkbox")
      ) {
        jsonConfig.value[index].paramValue = jsonConfig.value[index].paramValue.split(
          ","
        );
      }
      if (jsonConfig.value[index].type == "text_hint") {
        jsonConfig.value[index].variables.forEach((el: any) => {
          el.desc = `${el.desc}:${el.val}`;
        });
      }
    });

    console.log('[ jsonConfig.value ]', jsonConfig.value)
    // 初始化关联关系
    jsonConfig.value.forEach((item: any) => {
      paramValueOnChange(item)
    })
  } else {
    jsonConfig.value = [];
  }
};

const submitForm = async () => {
  loading.value = true;
  let requestObj = {};
  jsonConfig.value.forEach((item: any) => {
    // if(item.type == 'select_more' || item.type == 'checkbox') {

    // }
    // requestObj[item.paramName] = item.paramValue;
    requestObj[item.paramName] = String(item.paramValue);
  });

  ruleForm.value.jsonConfig = JSON.stringify(requestObj);

  // return

  let params = JSON.parse(JSON.stringify(ruleForm.value));
  params.externalType;
  if (addConfigData?.value) {
    params["id"] = addConfigData?.value.id;
  }
  let rs: any = await sysConfigApi.saveOrUpdateConfig(params);
  if (rs.code === 200) {
    ElMessage.success(`${addConfigData?.value ? "编辑" : "添加"}成功`);
    confirm();
  }
  loading.value = false;
};

const confirm = () => {
  emit("confirm");
  cancel();
};

const cancel = () => {
  qrcode.value='';
  verify.value='';
  emit("cancel", "addConfigDialog");
  ruleForm.value = {
    name: "",
    remark: "",
    unique: "",
    externalType: "", // 大类
    externalPlatformType: "", // 平台类型
    jsonConfig: "",
  };
  jsonConfig.value = [];

  ruleFormRef.value?.resetFields();
};
const emit = defineEmits(["confirm", "cancel"]);
defineExpose({ cancel });
</script>

<style lang="scss" scoped>
:deep(.el-input-number) {
  width: 100%;
}
.el-form {
  // padding-right: 80px;
}
.enumeration {
  display: flex;
  width: 100%;
  .el-form-item {
    width: 100%;
  }
  .operation {
    width: 50px;
    font-size: 18px;
    margin: 0 0 18px 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-icon {
      cursor: pointer;
    }
    .el-icon:hover {
      color: var(--el-color-primary);
    }
  }
}
.icon-add {
  margin: 0 5px;
}
.switch {
  display: flex;
}
.box-card {
  margin-bottom: 20px;
}
.ruleForm-w {
  // width: 90%;
}

.el-select {
  width: 100%;
}
:deep(.el-autocomplete) {
  width: 100%;
}

.scan-qrcode{
  display: flex;
  flex-direction:column;
  align-items: center;
}

.qrcode-wrapper {
  width: 100px;
  height: 100px;
  background: white;
  border-radius: 15px;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;

  .qrcode {
    width: 100%;
    height: 100%;
  }
}

.status-cover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(230, 230, 230, 0.9);
  color: var(--el-color-error);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.scan-tips {
  color: rgba(0, 0, 0, 0.7);
  font-size: 12px;
  margin-top: 10px
}
.scan-tips-font {
  color: var(--el-color-error);
  font-size: 14px;
}
</style>
